<template>
  <el-select
    v-model="model"
    :multiple="multiple"
    placeholder="请选择"
    @change="change"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.realName"
      :value="item.communityMemberId"
    />
    <template #empty>
      <div v-if="loadError" class="my-2">
        <div class="mb-2">数据加载失败</div>
        <el-button type="primary" size="small" @click="getMemberList"
          >重新加载</el-button
        >
      </div>
      <div v-else>
        <div class="my-2">暂无数据</div>
        <el-button type="primary" size="small" @click="getMemberList"
          >重新加载</el-button
        >
      </div>
    </template>
  </el-select>
</template>

<script setup>
import { toRaw } from "vue";
import { cloneDeep } from "lodash";
import { getCommunityMemberPage } from "@/api/realEstateManage";
const props = defineProps({
  multiple: {
    type: Boolean,
    default: false,
  },
});
const loadError = ref(false);
const emit = defineEmits(["change"]);
const model = defineModel();

const options = ref([]);

const getMemberList = async () => {
  loadError.value = false;
  try {
    const res = await getCommunityMemberPage({
      pageNo: 1,
      pageSize: 9999,
      ...props.params,
    });
    options.value = res.data.records;
  } catch (error) {
    loadError.value = true;
  }
};
onMounted(() => {
  getMemberList();
});
const change = (value) => {
  if (props.multiple) {
    const findItem = toRaw(options.value).filter((item) =>
      value.includes(item.communityMemberId)
    );
    emit("change", value, cloneDeep(findItem));
  } else {
    const findItem = toRaw(options.value).find(
      (item) => item.communityMemberId === value
    );
    emit("change", value, cloneDeep(findItem));
  }
};
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>
